package com.fr.plugin.filter;

import com.fr.decision.authority.data.User;
import com.fr.decision.webservice.v10.login.LoginService;
import com.fr.decision.webservice.v10.login.TokenResource;
import com.fr.decision.webservice.v10.user.UserService;
import com.fr.log.FineLoggerFactory;
import com.fr.third.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
public class FRLoginService {
    /**
     * 判断帆软是不是已经登录了
     *
     * @param req
     * @return
     */
    public Boolean isLoginedFR(HttpServletRequest req) {
        String token = TokenResource.COOKIE.getToken(req);
        try {
            LoginService.getInstance().loginStatusValid(token, null);
            return Boolean.valueOf(true);
        } catch (Exception localException) {
        }
        return Boolean.valueOf(false);
    }

    /**
     * 获取帆软当前登录的用户名
     *
     * @param req
     * @return
     */
    public String getFRCurrentName(HttpServletRequest req) {
        return LoginService.getInstance().getCurrentUserNameFromRequestCookie(req);
    }

    /**
     * 根据用户名登录帆软
     * @param req
     * @param res
     * @param userName 用户名
     * @return
     */
    public Boolean loginFR(HttpServletRequest req, HttpServletResponse res, String userName) {
        try {
            User u = UserService.getInstance().getUserByUserName(userName);
            if (u != null) {
                String token = LoginService.getInstance().login(req, res, userName);
                req.setAttribute("fine_auth_token", token);
                return true;
            } else {
                FineLoggerFactory.getLogger().error("{} 用户不存在帆软", userName);
                // WebUtils.writeOutTemplate("/com/fr/web/sso/filter/error.html", res, new HashMap());
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
